package org.zoomdev.android.nfccard.cpu;



import com.zoomdev.android.hex.HexUtil;

import org.zoomdev.android.nfc.adapters.ApduException;
import org.zoomdev.android.nfc.adapters.ApduResponse;
import org.zoomdev.android.nfc.adapters.IsoDepTagAdapter;
import org.zoomdev.android.nfccard.CardOperator;
import org.zoomdev.android.nfccard.CardTradeLog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CpuCard implements CardOperator {
    public static final byte TRANS_CSU = 6;
    public static final byte TRANS_CSU_CPX = 9;

    public CpuCard() {
    }

    public void selectFile(IsoDepTagAdapter adapter, boolean byName, String file) throws IOException, ApduException {
        if (file.length() % 2 > 0) {
            throw new RuntimeException("文件标识或者名称长度必须为偶数");
        } else {
            Utils.send(adapter,String.format("00a4%s00%02x%s", byName ? "04" : "00", file.length() / 2, file));
        }
    }

    public String getFile(IsoDepTagAdapter adapter, int sfi) throws IOException, ApduException {
        String apdu = String.format("00b0%02x0000", 128 | sfi);
        ApduResponse response = Utils.send(adapter,apdu);
        return response.getStr();
    }

    public int getBalance(IsoDepTagAdapter adapter) throws IOException, ApduException {
        ApduResponse response = Utils.send(adapter,"805C000204");
        int value = Integer.parseInt(response.getStr(), 16);
        return value;
    }

    public List<CardTradeLog> getTradeLogs(IsoDepTagAdapter adapter) throws IOException, ApduException {
        List<CardTradeLog> result = new ArrayList();

        for (int i = 1; i <= 10; ++i) {
            try {
                ApduResponse response = Utils.send(adapter,String.format("00b2%sc400", HexUtil.int2HexStr(i, 2)));
                byte[] v = response.getRowData();
                int cash = HexUtil.toInt(v, 5, 4);
                if (cash > 0) {
                    CardTradeLog vo = new CardTradeLog();
                    vo.setTime(String.format("%02X%02X.%02X.%02X %02X:%02X ", v[16], v[17], v[18], v[19], v[20], v[21], v[22]));
                    vo.setType(v[9] != 6 && v[9] != 9 ? 1 : 0);
                    vo.setCash(String.format("%.02f", (float) cash / 100.0F));
                    result.add(vo);
                }
            } catch (ApduException var8) {
                break;
            }
        }

        return result;
    }
}
